package yaner.hotel.manager.common.utils;

public class SnowUtils {
    // 起始的时间戳（通常是某个固定过去的时间点）
    private final long twepoch = 1288834974657L;

    // 机器ID所占的位数
    private final long workerIdBits = 5L;
    // 数据中心ID所占的位数
    private final long datacenterIdBits = 5L;
    // 最大机器ID
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 最大数据中心ID
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    // 序列号占用的位数
    private final long sequenceBits = 12L;

    // 机器ID左移位数
    private final long workerIdShift = sequenceBits;
    // 数据中心ID左移位数
    private final long datacenterIdShift = sequenceBits + workerIdBits;
    // 时间截左移位数
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    // 序列号掩码
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    // 上次生成ID的时间截
    private long lastTimestamp = -1L;
    // 序列号
    private long sequence = 0L;

    // 工作机器ID
    private final long workerId;
    // 数据中心ID
    private final long datacenterId;

    public SnowUtils(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public static String nextId() {
        SnowUtils idWorker = new SnowUtils(0, 0);
        return String.valueOf(idWorker.generateId());
    }

    public synchronized long generateId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift) // 时间截左移
                | (datacenterId << datacenterIdShift) // 数据中心ID左移
                | (workerId << workerIdShift) // 机器ID左移
                | sequence; // 序列号
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }
}
